<template>
	<w-container id="container">
		<u-status-bar></u-status-bar>
		<w-navbar></w-navbar>
		<!-- 中心区域 -->
		<!-- <w-image src="/static/icon/logo-text.png" :width="206" :height="177" class="top-img"></w-image> -->
		
		<view class="login_center flex flex-dir-col">
			<block v-if="initLoginType == 1">
				<view @click="$u.route('pages/login/register')" class="font-color-theme text-right">注册</view>
				<u-gap height="80"></u-gap>
				<view class="flex flex-dir-col flex-ai-center">
					<!-- <w-image :src="appConfig.appLogo" style="width: 82px;height: 82px;"></w-image> -->
					<image src="/static/logo.png" style="width: 82px;height: 82px;"></image>
					<u-gap height="100"></u-gap>
					<view @tap="initLoginType = 2" class="font-color-theme mb-24">其他手机号登录</view>
					<!-- #ifdef APP -->
					<w-button style="width: 289px;" @click="OneClicklogin">{{handleLang('一键登录')}}</w-button>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<w-button @click="H5OneLogin" style="width: 289px;">{{handleLang('一键登录')}}</w-button>
					<!-- #endif -->
					<input class="code-input mt-24" type="text" v-model="form2.inviter_code" placeholder="邀请码（选填)" />
				</view>
				<u-gap height="45"></u-gap>
				<view class="agreement">
					<w-agreement v-model="checked">
						<template>
							{{handleLang('我已阅读并同意')}}
								
							<text class="font-color-theme"
								@tap.stop="toWebview('/index/index/usageterms','用户服务协议')">{{handleLang('《用户服务协议》')}}</text>
							<text class="font-color-theme"
								@tap.stop="toWebview('/index/index/agreement','隐私政策')">{{handleLang('《隐私政策》')}}</text>
								
						</template>
					</w-agreement>
					<u-safe-bottom></u-safe-bottom>
				</view>
			</block>
			<block v-if="initLoginType == 2">
				<view class="font-size-22 font-w-500">欢迎登录{{ appConfig.appName }}</view>
				<view class="font-size-12 mt-8" style="color: #929292;">欢迎来到{{ appConfig.appName }}</view>
				<view class="loginInput">
					<view class="warp">
						
						<!-- 账号密码 -->
						<block v-if="loginType==1">
							<view class="iptStyle mt-10">
								<u-input key="1" v-model="form.account" type="text" @input="form2.mobile=$event"
									:customStyle="iptStyle" clearable :placeholder="handleLang('请输入本人实名认证的手机号')" border="bottom"
									fontSize="14" :color="inputColor">
									<template #prefix>
										<view class="flex flex-ai-center">
											<view class="font-size-15 font-w-500">+86</view>
											<u-line direction="col" length="20" margin="0 20rpx" color="#D9D9D9"></u-line>
										</view>
									</template>
								</u-input>
								<u-line></u-line>
							</view>
							<view class="iptStyle mt-20">
								<u-input key="2" v-show="ispwd" :password="true" v-model="form.password"
									:customStyle="iptStyle" clearable :placeholder="handleLang('请输入密码')" border="bottom"
									fontSize="14" :color="inputColor">
									<!-- <view slot="prefix" class="mr-20">密 码</view> -->
									<template slot="suffix" v-if="form.password">
										<w-icon name="eye-off" color="#909399" @click="ispwd=!ispwd" size="18"></w-icon>
									</template>
								</u-input>
								<u-input key="3" v-show="!ispwd" :password="false" v-model="form.password"
									:customStyle="iptStyle" clearable :placeholder="handleLang('请输入密码')" border="bottom"
									fontSize="14" :color="inputColor">
									<!-- <view slot="prefix" class="mr-20">密 码</view> -->
									<template slot="suffix" v-if="form.password">
										<w-icon name="eye-fill" color="#909399" @click="ispwd=!ispwd" size="18"></w-icon>
									</template>
								</u-input>
								<u-line></u-line>
							</view>
							<view class="iptStyle mt-20">
								<u-input key="5" v-model="form2.inviter_code" :customStyle="iptStyle" clearable
									:placeholder="handleLang('邀请码（选填)')" border="bottom" fontSize="14" :color="inputColor"
									maxlength="6">
								</u-input>
							</view>
							<u-line margin="0rpx 0 0"></u-line>
						</block>
				
						<!-- 账号验证码 -->
						<block v-if="loginType==2">
							<view class="iptStyle mt-20">
								<u-input key="1" v-model="form.account" type="text" @input="form2.mobile=$event"
									:customStyle="iptStyle" clearable :placeholder="handleLang('请输入本人实名认证的手机号')" border="bottom"
									fontSize="14" :color="inputColor">
									<template #prefix>
										<view class="flex flex-ai-center">
											<view class="font-size-15 font-w-500">+86</view>
											<u-line direction="col" length="20" margin="0 20rpx" color="#D9D9D9"></u-line>
										</view>
									</template>
								</u-input>
								<u-line></u-line>
							</view>
							<view class="iptStyle mt-20">
								<u-input key="5" v-model="form2.captcha" :customStyle="iptStyle" clearable
									:placeholder="handleLang('请输入验证码')" border="bottom" fontSize="14" :color="inputColor"
									maxlength="6">
									<!-- <view slot="prefix" class="mr-20">验证码 </view> -->
									<template slot="suffix">
										<u-code ref="uCode" @change="tips=$event" @start="isSend=false" @end="isSend=true"
											seconds="60" :changeText="handleLang('(重新发送 Xs)')" uniqueKey="login_page"
											keepRunning></u-code>
										<view @tap="checkVerifyStatus"
											:class="`font-size-12 ${isSend?'font-color-theme':'font-color-minor'}`">
											{{ handleLang(tips) }}
										</view>
									</template>
									<u-line></u-line>
								</u-input>
							</view>
							<u-line margin="0rpx 0 0"></u-line>
							<view class="iptStyle mt-20">
								<u-input key="5" v-model="form2.inviter_code" :customStyle="iptStyle" clearable
									:placeholder="handleLang('邀请码（选填)')" border="bottom" fontSize="14" :color="inputColor"
									maxlength="6">
								</u-input>
							</view>
							<u-line margin="0rpx 0 0"></u-line>
						</block>
						<!-- <u-gap height="30"></u-gap> -->
						<view class="action">
							<text
								@click="loginType = loginType==1?2:1">{{ handleLang(loginType==1 ? '短信登录': '密码登录' )}}</text>
							<text @click="$u.route('pages/login/forgetPwd')" v-if="loginType==1">{{handleLang('忘记密码？')}}</text>
						</view>
				
						<w-button class="login_btn" type="colorful" shape="circle"
							@click="$u.throttle(loginChange, 500)">{{handleLang('登录')}}</w-button>
						<!-- #ifdef APP -->
									<!-- 	<w-button class="login_btn" type="light" shape="circle"
							@click="OneClicklogin">{{handleLang('手机号一键登录')}}</w-button> -->
						<!-- #endif -->	
						<!-- #ifdef H5 -->
						<!-- <w-button class="login_btn" type="light" shape="circle"
						@click="H5OneLogin">{{handleLang('手机号一键登录')}}</w-button> -->
						<!-- #endif -->
						<view class="agreement mt-20">
							<w-agreement v-model="checked">
								<template>
									{{handleLang('我已阅读并同意')}}
				
									<text class="font-color-theme"
										@tap.stop="toWebview('/index/index/usageterms','用户服务协议')">{{handleLang('《用户服务协议》')}}</text>
									<text class="font-color-theme"
										@tap.stop="toWebview('/index/index/agreement','隐私政策')">{{handleLang('《隐私政策》')}}</text>
				
								</template>
							</w-agreement>
							<u-safe-bottom></u-safe-bottom>
						</view>
						<!-- <u-gap height="200"></u-gap>
						<view class="register_btn font-color-theme" @click="$u.route('pages/login/register')">
							{{handleLang('去注册')}} 
						</view> -->
					</view>
				
				</view>
			</block>
		</view>

		<w-jy-verify ref="captcha" v-if="captchaStatus" @success='getCode'></w-jy-verify>
	</w-container>
</template>

<script>
	import {
		sendSms,
		login,
		aliPhoneOauth,
		aliH5GetAuthToken,
		aliH5PhoneOauth
	} from '@/api/user/index.js';
	import {
		TokenKey   
	} from '@/config';
	import {
		mapActions,
		mapState
	} from 'vuex';
	import {
		getTest
	} from '@/api/common/index.js'
	import authUiConfig from "./authUiConfig"
	// #ifdef APP
	const aLiSDKModule = uni.requireNativePlugin('AliCloud-NirvanaPns');
	aLiSDKModule.setAuthSDKInfo(authUiConfig.securityKey());
	// #endif
	// #ifdef H5
	import { PhoneNumberServer } from 'aliyun_numberauthsdk_web'; 
	var phoneNumberServer = new PhoneNumberServer();
	// #endif
	export default {
		data() {
			return {
				initLoginType:1,   //1代表初始进入 2代表其他方式登录
				checked: false, //  协议勾选
				isSend: true, //  验证码状态
				tips: '获取验证码', //  验证码
				iptStyle: {
					'height': '80rpx',
					'padding': '24rpx 32rpx',
					background: '#fff',
					"borderRadius": "16rpx"
				},
				inputColor: '#222',
				loginType: 2, // 1密码登录，2验证码登录
				ispwd: true,
				form: {
					account: null,
					password: null,
					inviter_code:''
				},
				form2: {
					mobile: null,
					captcha: null,
					inviter_code:''
				}
			};
		},

		computed: {
			...mapState('config', {
				logo(state) {
					return state.info.appLogo
				},
				isAgreement(state) {
					return state.info.isAgreement
				},
				captchaStatus(state) {
					return !!Number(state.info.puzzleCaptcha)
				}
			})
		},
		onSHow(){
			this.initLoginType = 1
		},
		watch: {
			isAgreement: {
				handler: function(val) {
					this.checked = val == 1
				},
				immediate: true
			}
		},
		methods: {
			...mapActions('user', ['getUserInfo']),
			checkVerifyStatus() {
				if (!this.form2.mobile) {
					uni.$u.toast('请输入手机号');
					return
				} else if (this.form2.mobile.length != 11) {
					uni.$u.toast('请输入11位手机号');
					return
				}
				if (this.captchaStatus) {
					this.$refs.captcha.showCaptcha();
				} else {
					this.getCode();
				}
			},
			// 获取验证码
			getCode(validate) {
				if (!this.form2.mobile) {
					uni.$u.toast('请输入手机号');
					return
				} else if (this.form2.mobile.length != 11) {
					uni.$u.toast('请输入11位手机号');
					return
				}
				if (this.$refs.uCode.canGetCode) {
					this.isSend = true
					uni.showLoading()
					sendSms({
						mobile: this.form2.mobile,
						event: "login",
						...validate
					}).then(res => {
						this.$refs.uCode.start();
						uni.hideLoading();
					}).catch(() => {
						uni.hideLoading();
					})
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			verify() {
				this.verifyReady = true;
			},
			verifyRes(data, res) {
				if (res) {
					getTest(res).then(res => {
						console.log(res)
					})
				}
			},
			// 登录
			loginChange() {
				if (!this.checkForm()) return;
				let loginType = this.loginType;
				let form = loginType == 1 ? this.form : this.form2;
				uni.showLoading({
					mask: true,
					title: "登录中..."
				});

				if (uni.getStorageSync("invite_code") && loginType == 2) {
					this.form2.inviter_code = uni.getStorageSync("invite_code")
				}
				login(form, loginType).then(res => {
					//保存token
					let {
						event,
						sms_code
					} = res.data
					uni.setStorageSync(TokenKey, res.data.userinfo.token)
					uni.setStorageSync('isNewUser', res.data.userinfo.is_exist == 0)
					//获取用户信息
					uni.$emit('loginStatus', true)
					this.getUserInfo().then(() => {
						uni.showToast({
							icon: 'success',
							title: '登录成功',
							success: () => {
								// this.$tools.loginSuccessBack()
								setTimeout(()=>{
									uni.switchTab({ url:"/pages/index/index" })
								},1500)
							}
						})
					})
				}).catch((err) => {
					console.log(err);
				})
			},
			async H5OneLogin(){
				uni.showLoading({
					title:'获取中...'
				})
				const { code,data } = await aliH5GetAuthToken()
				uni.hideLoading()
				if(code != 1) return 
				this.checkLogin(data.jwtToken,data.accessToken)
			},
			checkLogin(jwtToken, accessToken) {
				let _this = this
				uni.showLoading({
					title:'验证中...'
				})
			  phoneNumberServer.checkLoginAvailable({
			    accessToken: accessToken,
			    jwtToken: jwtToken,
			    success: function (res) {
					uni.hideLoading()
			      console.log("身份鉴权成功, 可唤起登录界面", res);
			      _this.getToken();
			    },
			
			    error: function (res) {
					_this.initLoginType = 2
					uni.showToast({
						title:'身份鉴权失败,关闭Wi-Fi或者尝试其他登录方案',
						icon:'none'
					})
					uni.hideLoading()
			      console.log("身份鉴权失败", res);
			    },
			  });
			},
			getToken() {
			  let _this  = this
			  uni.showLoading({
			  	title:'token获取中...'
			  })
			  phoneNumberServer.getLoginToken({
			    // 成功回调
			    success: function (res) {
					uni.hideLoading()
			      // 一键登录: 可发请求到服务端调用 GetPhoneWithToken API, 获取用户手机号, 完成登录
				  _this.getH5PhoneOauth(res.spToken)
			    },
			    // 失败回调
			    error: function (res) {
					uni.hideLoading()
					_this.initLoginType = 2
					console.log(res,'失败回调');
					uni.showToast({
						title: res.msg,
						icon:'none'
					})
				},
			    // 授权页状态监听函数
			    watch: function (status, data) {
					uni.hideLoading()
					console.log(status,data,'监听授权');
				},
			    // 配置选项
			    authPageOption: {
			      navText: "一键登录",
			      subtitle: "", // 副标题
			      btnText: "立即登录",
			      agreeSymbol: "、",
			      showCustomView: true,
			      // customView: {
			      //   element:
			      //     '<div class="btn_box other" onclick="clickEvent()">切换其他登录方式</div>',
			      //   style: ".btn_box.other{background: #fff; color: #f00}",
			      //   js: "function clickEvent(){alert(666666)}",
			      // },
			      privacyBefore: "我已阅读并同意",
			      isDialog: true, // 是否是弹窗样式
			      manualClose: true, // 是否手动关闭弹窗/授权页
			    },
			  });
			},
			async getH5PhoneOauth(spToken){
				// console.log(spToken,'spToken的值');
				// return
				phoneNumberServer.closeLoginPage(); // 调用此方法手动关闭授权页。
				let _this = this
				uni.showLoading({
					title:'登录中...'
				})
				const { code,data } = await aliH5PhoneOauth({spToken:spToken,inviter_code:this.form2.inviter_code})
				if(code != 1) return
				uni.setStorageSync(TokenKey, data.userinfo.token)
				uni.setStorageSync('isNewUser', data.userinfo.is_exist == 0)
				//获取用户信息
				uni.$emit('loginStatus', true)
				_this.getUserInfo().then(() => {
					uni.showToast({
						icon: 'success',
						title: '登录成功',
						success: () => {
							_this.$tools.loginSuccessBack()
						}
					})
				})
			},
			OneClicklogin() {
				let _this = this
				if (!this.checked) {
					uni.$u.toast('请先勾选用户协议');
					return false;
				}
				aLiSDKModule.quitLoginPage()
				aLiSDKModule.accelerateLoginPage(5000, (result) => {
					if ("600000" == result.resultCode) {
						console.log("加速成功");
					}
				});
				aLiSDKModule.getLoginToken(
					5000,
					authUiConfig.authUiConfig,
					tokenResult => {
						console.log('回调了', tokenResult);
						// return
						if ("600001" == tokenResult.resultCode) {} else if ("600000" == tokenResult.resultCode) {
							console.log("获取Token成功，接下来拿着结果里面的Token去服务端换取手机号码，SDK服务到此结束")
							let form = {
								accessToken: tokenResult.token,
								inviter_code: _this.form2.inviter_code,
								outId: authUiConfig.getOutId()
							}
							aLiSDKModule.quitLoginPage()
							uni.showLoading({
								title: '登录中...',
								mask: true
							})
							aliPhoneOauth(form).then(response => {
								uni.setStorageSync(TokenKey, response.data.userinfo.token)
								uni.setStorageSync('isNewUser', response.data.userinfo.is_exist == 0)
								//获取用户信息
								uni.$emit('loginStatus', true)
								_this.getUserInfo().then(() => {
									aLiSDKModule.quitLoginPage()
									uni.showToast({
										icon: 'success',
										title: '登录成功',
										success: () => {
											_this.$tools.loginSuccessBack()
										}
									})
								})
							}).catch( err => {
								// plus.nativeUI.closeWaiting()
								// console.log(err);
							})
							//手动关闭授权页

						} else {
							//其他失败情况，手动关闭授权页
							aLiSDKModule.quitLoginPage()
							uni.showModal({
								title: '温馨提示',
								content: '一键换启登录失败,请尝试打开使用数据流量，再次一键登录',
								showCancel: false,
								confirmColor: "#7000FF",
								confirmText: '知道了'
							})
						}
					},
					clickResult => {
						console.log(clickResult, 'jieguo');
						switch (clickResult.resultCode) {
							case "700000":
								console.log("用户点击返回按钮")
								break
							case "700001":
							_this.initLoginType = 2
								console.log("用户切换其他登录方式")
								break
							case "700002":
								//通过isChecked字段可以得到checkbox是否勾选，未勾选可以用自定义Toast进行提示
								
								console.log(clickResult.result.isChecked,'222');
								if(!clickResult.result.isChecked) {
									plus.nativeUI.toast("请认真阅读服务条款");
								}
								console.log("用户点击登录按钮")
								break
							case "700003":
								console.log("用户点击checkBox")
								break
							case "700004":
								console.log("用户点击协议")
								break
							case "700010":
								//调用userControlAuthPageCancel后方可使用
								console.log("用户点击返回按钮，Android专用");
								break
							case "700011":
								//调用userControlAuthPageCancel后方可使用
								console.log("用户使用物理返回键，Android专用");
								break
						}
					},
					customUiResult => {
						//这里回调的是自定义控件的点击事件，通过 customUiResult.widgetId 来识别自定义控件，然后做一些自己的处理
					}
				)
			},
			// 验证
			checkForm() {
				if (!this.checked) {
					uni.$u.toast('请先勾选用户协议');
					return false;
				}
				if (!this.form.account && this.loginType == 1) {
					uni.$u.toast('请输入手机号');
					return false;
				}
				if (!this.form.password && this.loginType == 1) {
					uni.$u.toast('请输入登录密码');
					return false;
				}
				if (!this.form2.mobile && this.loginType == 2) {
					uni.$u.toast('请输入手机号');
					return false;
				}
				if (!this.form2.captcha && this.loginType == 2) {
					uni.$u.toast('请输入验证码');
					return false;
				}
				return true
			}
		}
	}
</script>

<style lang="scss">
	page { background-color: #FFFFFF; }
	#container {
		@extend .flex, .flex-dir-col;
		position: relative;
		background-color: #FFFFFF;
		padding-top: 72rpx;
	}

	.top-img {
		margin: 0 auto;
	}

	// #navbarStyle /deep/ .u-navbar__content{
	// 	background-image: url('@/static/bg/login.png');
	// 	background-position: top;
	// 	background-size: 100% auto;
	// }
	.login_center {
		width: 100%;
		padding: 32rpx;
		box-sizing: border-box;
		@extend .flex, .flex-dir-col, .flex-1;
		// margin-top: 100rpx;
		position: relative;
		z-index: 10;

		// /deep/ .input-placeholder{
		// 	font-size: 28rpx;
		// }
		>.title {
			width: 100%;
			@extend  .flex, .flex-dir-col;

			.title-style {
				// background-image: $theme-jb-color;// 使用该属性进行渐变
				// color: transparent;//默认颜色设置透明
				-webkit-background-clip: text;
				// color: #fff;
			}
		}

		.loginInput {
			width: 100%;
			box-sizing: border-box;
			height: 65vh;
			// padding: 0 60rpx;
			// margin-top: 74rpx;

			.warp {
				width: 100%;
				// padding: 36rpx 32rpx;
				// background: #F5F5F5;
				border-radius: 16rpx;
				z-index: 9999;

				>.iptStyle {
					// width: 100%;
					background: rgba(0, 0, 0, 0.06);
					border-radius: 64rpx;
					// padding: 0 30rpx;
					box-sizing: border-box;

					.u-border-bottom {
						border-color: transparent !important;
					}
				}

				>.action {
					width: 100%;
					height: 80rpx;
					color: $theme-color;
					@extend .flex-center, .flex-js-sb, .font-size-14;

					>text {
						display: inline-block;
						height: 100%;
						line-height: 80rpx;
					}
				}

				>.login_btn {
					width: 100%;
					margin-top: 24rpx;
				}

				>.register_btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					margin: 20rpx 0;
					@extend .font-size-14;
				}
			}
		}




	}

	.agreement {
		width: 100%;
		// padding: 0 50rpx 40rpx;
	}
	.code-input {
		width: 289px;
		height: 50px;
		background: #F5F5F5;
		border-radius: 25px 25px 25px 25px;
		text-align: center;
	}
</style>